//
//  Topic.m
//  MHO
//
//  Created by papo on 4/2/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "Topic.h"
#import "ServiceLib.h"
#import "SBJson.h"
#import "Lib.h"
#import "Contants.h"

@implementation Topic

+ (NSMutableArray*)topicFromCat:(NSString *)cat {
    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/TopicCat?IdCat=%@&key=%@", cat, kServerKey];

    return [self topicFromUrl:url];
}

+ (NSMutableArray*)topicFromUrl:(NSString *)url {
    NSMutableArray* data = [[NSMutableArray alloc] init];

    NSString* retVal = [ServiceLib sendGetRequest:url];
    if (retVal) {
        SBJsonParser* parser = [[SBJsonParser alloc] init];
        id result = [parser objectWithString:retVal];
        if (result && [result isKindOfClass:[NSDictionary class]]) {
            if ([result objectForKey:@"Ret"] && [[result objectForKey:@"Ret"] intValue] > 0) {
                NSArray* array = [result objectForKey:@"Data"];
                if (array && [array isKindOfClass:[NSArray class]]) {
                    for (NSDictionary* dict in array) {
                        if (dict) {
                            Topic* t = [Topic topicFromDictionary:dict];
                            if (t) {
                                [data addObject:t];
                            }
                        }
                    }
                }
            }
        }
    }
    return data;
}

+ (Topic*)topicFromDictionary:(NSDictionary *)dict {
    return [[Topic alloc] initWithDictionary:dict];
}

- (id)initWithDictionary:(NSDictionary *)dict {
    self = [super init];
    if (self) {
        self.topicId = numberCheckNull([dict objectForKey:@"Id"]);
        self.topicName = strCheckNull([dict objectForKey:@"Name"]);
//        self.description = strCheckNull([dict objectForKey:@"Description"]);
//        self.imageUrl = strCheckNull([dict objectForKey:@"Image"]);
    }
    return self;
}

- (NSString*)description {
    return [NSString stringWithFormat:@"Topic id: %@", self.topicId];
}
@end
